const express = require('express');
const path = require('path');
const multer = require('multer');
const router = express.Router();
const userCtrl = require('./controls/userCtrl');
const bookCtrl = require('./controls/booksCtrl');
const orderCtrl = require('./controls/orderCtrl');
const commentCtrl = require('./controls/commentCtrl');
const dashboardCtrl = require('./controls/dashboardCtrl');
const checkToken = require('./utils/checkToken');
const fs = require('fs');

// 确保avatars文件夹存在
const avatarsDir = path.join(__dirname, 'public/uploads/avatars');
if (!fs.existsSync(avatarsDir)){
  fs.mkdirSync(avatarsDir, { recursive: true });
  console.log('创建头像存储文件夹:', avatarsDir);
}

// 确保book covers文件夹存在
const bookCoversDir = path.join(__dirname, 'public/uploads/books');
if (!fs.existsSync(bookCoversDir)){
  fs.mkdirSync(bookCoversDir, { recursive: true });
  console.log('创建图书封面存储文件夹:', bookCoversDir);
}

// 配置头像上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, avatarsDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, 'avatar-' + uniqueSuffix + ext);
  }
})

const upload = multer({ 
  storage: storage,
  limits: { fileSize: 2 * 1024 * 1024 }, // 2MB限制
  fileFilter: function (req, file, cb) {
    if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
      cb(null, true);
    } else {
      cb(new Error('只接受JPG和PNG格式的图片'), false);
    }
  }
});

// 配置图书封面上传
const bookCoverStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, bookCoversDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, 'book-' + uniqueSuffix + ext);
  }
})

const uploadBookCover = multer({ 
  storage: bookCoverStorage,
  limits: { fileSize: 2 * 1024 * 1024 }, // 2MB限制
  fileFilter: function (req, file, cb) {
    if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
      cb(null, true);
    } else {
      cb(new Error('只接受JPG和PNG格式的图片'), false);
    }
  }
});

// 头像上传路由
router.post('/upload/avatar', checkToken, (req, res, next) => {
  console.log('开始处理头像上传请求');
  upload.single('avatar')(req, res, function(err) {
    if (err) {
      console.error('头像上传错误:', err);
      if (err.message === '只接受JPG和PNG格式的图片') {
        return res.send({ code: 400, message: '只接受JPG和PNG格式的图片', data: null });
      }
      if (err.code === 'LIMIT_FILE_SIZE') {
        return res.send({ code: 400, message: '文件大小不能超过2MB', data: null });
      }
      return res.send({ code: 500, message: '头像上传失败: ' + err.message, data: null });
    }
    
    if (!req.file) {
      console.log('未找到上传的文件');
      return res.send({ code: 400, message: '未上传文件或文件格式不正确', data: null });
    }
    
    // 保存头像路径到用户记录（这里只返回路径，实际更新在updateAdminProfile中进行）
    // 确保路径以/开头，前端拼接URL时更加统一
    const avatarUrl = `/uploads/avatars/${req.file.filename}`;
    console.log('头像上传成功:', req.file);
    console.log('头像文件路径:', req.file.path);
    console.log('返回的头像URL:', avatarUrl);
    
    // 测试文件是否可访问
    const fullPath = path.join(__dirname, 'public', 'uploads', 'avatars', req.file.filename);
    console.log('头像完整物理路径:', fullPath);
    console.log('文件是否存在:', fs.existsSync(fullPath) ? '是' : '否');
    
    res.send({ 
      code: 200, 
      message: '头像上传成功', 
      data: { 
        url: avatarUrl,
        filename: req.file.filename,
        fullUrl: `http://localhost:3000${avatarUrl}` // 提供完整URL，以防前端需要
      }
    });
  });
});

// 图书封面上传路由
router.post('/upload/bookcover', checkToken, (req, res, next) => {
  console.log('开始处理图书封面上传请求');
  uploadBookCover.single('cover')(req, res, function(err) {
    if (err) {
      console.error('图书封面上传错误:', err);
      if (err.message === '只接受JPG和PNG格式的图片') {
        return res.send({ code: 400, message: '只接受JPG和PNG格式的图片', data: null });
      }
      if (err.code === 'LIMIT_FILE_SIZE') {
        return res.send({ code: 400, message: '文件大小不能超过2MB', data: null });
      }
      return res.send({ code: 500, message: '图书封面上传失败: ' + err.message, data: null });
    }
    
    if (!req.file) {
      console.log('未找到上传的文件');
      return res.send({ code: 400, message: '未上传文件或文件格式不正确', data: null });
    }
    
    // 返回封面路径
    const coverUrl = `/uploads/books/${req.file.filename}`;
    console.log('图书封面上传成功:', req.file);
    console.log('图书封面文件路径:', req.file.path);
    console.log('返回的图书封面URL:', coverUrl);
    
    res.send({ 
      code: 200, 
      message: '图书封面上传成功', 
      data: { 
        url: coverUrl,
        filename: req.file.filename,
        fullUrl: `http://localhost:3000${coverUrl}` // 提供完整URL
      }
    });
  });
});

// 管理员登录
router.post('/admin/login', userCtrl.adminLogin);

// 管理员资料相关路由
router.get('/admin/profile', checkToken, userCtrl.getAdminProfile);
router.put('/admin/profile', checkToken, userCtrl.updateAdminProfile);
router.put('/admin/password', checkToken, userCtrl.updateAdminPassword);

// 后台订单管理API
router.get('/admin/orders', checkToken, orderCtrl.adminGetAllOrders);
router.get('/admin/orders/:id', checkToken, orderCtrl.adminGetOrderDetail);
router.post('/admin/orders/ship', checkToken, orderCtrl.adminShipOrder);
router.post('/admin/orders/cancel/:id', checkToken, orderCtrl.adminCancelOrder);
router.get('/admin/orders/stats', checkToken, orderCtrl.adminGetOrderStats);

// 前台订单API
router.post('/orderList', checkToken, orderCtrl.doAddOrder);
router.get('/orderList', checkToken, orderCtrl.showOrders);
router.delete('/orderList/:id', checkToken, orderCtrl.deleteOrder);

// 导入并使用用户路由
router.use(require('./routes/users'));

module.exports = router;